/**
 * @file double_stack.cpp
 * @brief 共享栈的实现
 * @author Xavier ZXY (zxy_xavier@163.com)
 * @version : 1.0
 * @date 2022-04-24 03:33
 *
 */

#include "double_stack.h"
#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{

    SqDoubleStack s;
    if (InitStack(&s) == OK)
    {
        for (int i = 0; i < 5; i++)
        {
            Push(&s, i, 1);
        }
        for (int i = MAXSIZE; i > MAXSIZE - 3; i--)
        {
            Push(&s, i, 2);
        }
    }

    printf("栈中元素依次为：");
    int e;
    StackTraverse(s);

    printf("当前栈中元素有：%d \n", StackLength(s));

    Pop(&s, &e, 2);
    printf("弹出的栈顶元素 e=%d\n", e);
    printf("栈空否：%d(1:空 0:否)\n", StackEmpty(s));

    for (int j = 6; j <= MAXSIZE - 2; j++)
        Push(&s, j, 1);

    printf("栈中元素依次为：");
    StackTraverse(s);

    printf("栈满否：%d(1:否 0:满)\n", Push(&s, 100, 1));

    ClearStack(&s);
    printf("清空栈后，栈空否：%d(1:空 0:否)\n", StackEmpty(s));

    return 0;
}

//显示元素
Status visit(SElemType c)
{
    cout << c;
    return OK;
}

//构造一个空栈
Status InitStack(SqDoubleStack *S)
{
    S->top1 = -1;
    S->top2 = MAXSIZE;
    return OK;
}

//置为空栈
Status ClearStack(SqDoubleStack *S)
{
    S->top1 = -1;
    S->top2 = MAXSIZE;
    return OK;
}

//是否为空栈
Status StackEmpty(SqDoubleStack S)
{
    if (S.top1 == -1 && S.top2 == MAXSIZE)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

//栈中元素的个数
int StackLength(SqDoubleStack S)
{
    return (S.top1 + 1) + (MAXSIZE - S.top2);
}

//插入新的栈顶元素e
Status Push(SqDoubleStack *S, SElemType e, int stackNumber)
{
    if (S->top1 + 1 >= S->top2)
    {
        return ERROR;
    }
    if (stackNumber == 1)
    {
        S->data[++S->top1] = e;
    }
    else if (stackNumber == 2)
    {
        S->data[--S->top2] = e;
    }

    return OK;
}

//弹出栈顶元素并储存在e中
Status Pop(SqDoubleStack *S, SElemType *e, int stackNumber)
{
    if (stackNumber == 1)
    {
        if (S->top1 == -1)
        {
            return ERROR;
        }
        *e = S->data[S->top1--];
    }
    else if (stackNumber == 2)
    {
        if (S->top2 == MAXSIZE)
        {
            return ERROR;
        }
        *e = S->data[S->top2++];
    }

    return OK;
}

//遍历栈中的所有元素
Status StackTraverse(SqDoubleStack S)
{
    for (int i = 0; i <= S.top1; i++)
    {
        visit(S.data[i++]);
    }

    for (int i = S.top2; i < MAXSIZE; i++)
    {
        visit(S.data[i]);
    }

    cout << endl;
    return OK;
}